package com.imooc.framework.stream;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class DistinctDemo {

    public static void main(String[] args) {

        List<Employee> list = Employee.getEmpList();
        Stream<Employee> stream = list.parallelStream();
        List<Employee> result = stream.collect(collectingAndThen(
                toCollection(() -> new TreeSet<>(Comparator.comparing(Employee::getDept))),
                ArrayList::new));
        result.forEach(System.out::println);

        //根据age属性去重
//        list.stream().filter(distinctByKey(s -> s.getDept()))
//                .forEach(System.out::println);
    }


    //定义一个Predicate函数
    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }



}
